/*
* Author: Sowmya Kameswaran
*/
package com.foo.TemporalData;

import java.sql.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.foo.Entity.HistoricalData;
import com.foo.TextDataSender.DataSender;

/**
 * Session Bean implementation class TemporalDataProvider
 */
@Stateless(name="TemporalDataProvider")
public class TemporalDataProvider implements TemporalDataProviderRemote, TemporalDataProviderLocal {


	@PersistenceContext(unitName="temporalinformationprovider") // This is the entity manager required by the Entity bean
	private EntityManager em;

	int total =0 ;
	Query gettemporaldatabytime = null;
	List<HistoricalData> temporaldatalist = null;
	String snapshotmessage="";
	DataSender datasender = new DataSender();
	/**
	 * Default constructor. 
	 */
	public TemporalDataProvider() 
	{
		/*try
		{
			Properties properties = new Properties();
			properties.put(Context.PROVIDER_URL, "jnp://localhost:1099");
			properties.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
			properties.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
			Context ctx = new InitialContext(properties);
			Object ref = ctx.lookup("DataSender/remote");
			datasender = (DataSenderRemote) PortableRemoteObject.narrow(ref, DataSenderRemote.class);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}*/

		System.out.println("In server class to retrieve data \n"); 
	}

	
	@Override
	public void sendtemporalinfo(String sorttype, Date fromdate, Date todate) 
	{
		System.out.println("Entering server function Temporal Data with parameters " +sorttype + " "+fromdate + " " +todate);
	
		gettemporaldatabytime = em.createQuery("from HistoricalData d where d.ticker_symbol = :ticker_symbol and d.deals_date between :fromdate and :todate");
		gettemporaldatabytime.setParameter("ticker_symbol", sorttype );
		gettemporaldatabytime.setParameter("fromdate",fromdate );
		gettemporaldatabytime.setParameter("todate",todate );

		System.out.println("The query : " + gettemporaldatabytime.toString());
		temporaldatalist=gettemporaldatabytime.getResultList();
		int listsize = temporaldatalist.size();
		System.out.println("list size "+listsize);
		snapshotmessage="";

		for(int k=0;k<listsize;k++)
		{
			snapshotmessage += temporaldatalist.get(k).getTicker_symbol()+","+temporaldatalist.get(k).getDeals_date().toString()+","+temporaldatalist.get(k).getOpen_value()+","+temporaldatalist.get(k).getHigh_value()
			+","+temporaldatalist.get(k).getLow_value()+","+temporaldatalist.get(k).getClose_value()+","+temporaldatalist.get(k).getVolume()+",";
		}
		datasender.sendMessage("Temporal",snapshotmessage);
		System.out.println("The message " +snapshotmessage);
	}

}
